package my.dataCollection.base;

import java.util.List;

import my.dataCollection.base.vo.ParamVO;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class HCDataCrawler {
	
	
	public String crawlData(ParamVO param) throws Exception{
		
		if("POST".equals(param.getMethod().toUpperCase())){
			return crawlDataPost(param);
		}else{
			return crawlDataGet(param);
		}
		
	}
	
	private String crawlDataGet(ParamVO param) throws Exception {
		String rs = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(param.getHttpURL());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                
                if(response.getStatusLine().getStatusCode() == 200){
	            	rs = EntityUtils.toString(response.getEntity());
	            }
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	    return rs;
    }

	public String crawlDataPost(ParamVO param) throws Exception{
		
		String rs = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();

        try {

        	HttpPost httpPost = new HttpPost(param.getHttpURL());
            List<NameValuePair> params = param.getParams();
            if(!params.isEmpty()){
            	httpPost.setEntity(new UrlEncodedFormEntity(param.getParams()));
            }
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try{
            	if(response.getStatusLine().getStatusCode() == 200){
	            	rs = EntityUtils.toString(response.getEntity());
	            }
            }finally{
            	response.close();
            }

        } finally {
        	httpclient.close();
        }
        return rs;
	}
	
}
